//
//  DropdownboxView.m
//  eticket
//
//  Created by AnhQuocNguyen on 4/12/13.
//  Copyright (c) 2013 SoinMedia. All rights reserved.
//

#import "DropdownboxView.h"

@implementation DropdownboxView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.clipsToBounds = YES;
        self.layer.borderWidth = 1.;
        self.layer.cornerRadius = 2;
        self.layer.borderColor = [[UIColor colorWithRed:237/255 green:237/255 blue:237/255 alpha:.3] CGColor];
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)setupUI{
    
    ////////////////////////////////////////////////////////////////////////////
    //Setup tableView
    if (!_tblView) {
        _tblView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) style:UITableViewStylePlain];
        _tblView.backgroundColor = [UIColor clearColor];
        _tblView.delegate = self;
        _tblView.dataSource = self;
        [self addSubview:_tblView];
    }
    else{
        [_tblView reloadData];
    }
    
    ////////////////////////////////////////////////////////////////////////////
    //Pull to refresh
    if (refeshHeaderTableView == nil) {
        refeshHeaderTableView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _tblView.bounds.size.height, self.frame.size.width, _tblView.bounds.size.height)];
        refeshHeaderTableView.delegate = self;
        [_tblView addSubview:refeshHeaderTableView];
        [refeshHeaderTableView setBlackTextColor];
    }
    else{
        [self doneLoadingTableViewData];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_arrayListData count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"CountryCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        cell.exclusiveTouch = YES;
            [[cell textLabel] setFont:[UIFont systemFontOfSize:15.]];
    }
    
    cell.textLabel.text = [_typeAPI isEqualToString:countries_API] ? ((Country *)[_arrayListData objectAtIndex:indexPath.row]).title : ((CategoryEvent *)[_arrayListData objectAtIndex:indexPath.row]).title;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_dropdownboxViewDelegate respondsToSelector:@selector(DropdownboxView:didSelectedCountry:)]) {
        if ([_typeAPI isEqualToString:countries_API]) {
              [_dropdownboxViewDelegate DropdownboxView:self didSelectedCountry:[_arrayListData objectAtIndex:indexPath.row]];
        }
        else{
            [_dropdownboxViewDelegate DropdownboxView:self didSelectedCategory:[_arrayListData objectAtIndex:indexPath.row]];
        }
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//////////////////////////////////////////////////////////////////////////////////////////////
//Get Data from server
#pragma mark - getDataFromServer
- (void)getDataFromServer{
    dispatch_async(kBgQueue, ^{
        NSString *urlString = [NSString stringWithFormat:@"%@%@%@", URL_island_API, _typeAPI, TOKEN__island];
        NSURL *url = [NSURL URLWithString:urlString];
        
        requestServer = [ASIFormDataRequest requestWithURL:url];
        [requestServer setTimeOutSeconds:30];
        [requestServer setCompletionBlock:^{
            NSError *error = nil;
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:[requestServer responseData] options:kNilOptions error:&error];
            
            /////////////////////////////////////////////////////////////////////
            //Set error server
            if (error) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[error description] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
                alert.tag = ALERT_COMBOBOX_FINDEVENT;
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                return;
            }
            
            
            /////////////////////////////////////////////////////////////////////
            //Set error json
            NSDictionary *jsonError = [jsonDic objectForKey:@"error"];
            if ([[jsonError objectForKey:@"code"] intValue] != 200) {
                NSArray *messageArray = [jsonError objectForKey:@"message"];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[messageArray objectAtIndex:0] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
                alert.tag = ALERT_COMBOBOX_FINDEVENT;
                [alert show];
                SAFE_RELEASE_OBJECT(alert);
                return;
            }
            
            /////////////////////////////////////////////////////////////////////
            //Set Data
            NSDictionary *dicData = [jsonDic objectForKey:@"data"];
            NSArray *list = [dicData objectForKey:[_typeAPI isEqualToString:countries_API] ? @"countries" : @"categories"];
            
            
            SAFE_RELEASE_OBJECT(_arrayListData);
            _arrayListData = [[NSMutableArray alloc] init];
            
            //Add none vao dau tien
            if ([_typeAPI isEqualToString:countries_API]) {
                Country *country = [[Country alloc] init];
                country.title = @"NONE";
                country.idCountry = @"-100";
                country.slug = @"";
                [_arrayListData addObject:country];
                SAFE_RELEASE_OBJECT(country);
            }
            else{
                CategoryEvent *category = [[CategoryEvent alloc] init];
                category.title = @"NONE";
                category.idCategory = @"-100";
                [_arrayListData addObject:category];
                SAFE_RELEASE_OBJECT(category);
            }
            
            //Add object
            for (NSInteger i = 0; i < [list count]; i++) {
                NSDictionary *dic = [list objectAtIndex:i];
                if ([_typeAPI isEqualToString:countries_API]) {
                    Country *country = [[Country alloc] init];
                    country.title = [dic objectForKey:@"title"];
                    country.idCountry = [dic objectForKey:@"id"];
                    country.slug = [dic objectForKey:@"slug"];
                    [_arrayListData addObject:country];
                    SAFE_RELEASE_OBJECT(country);
                }
                else{
                    CategoryEvent *category = [[CategoryEvent alloc] init];
                    category.title = [dic objectForKey:@"title"];
                    category.idCategory = [dic objectForKey:@"id"];
                    [_arrayListData addObject:category];
                    SAFE_RELEASE_OBJECT(category);
                }
            }

            //Setup tableView & delegate
            [self decodeJson];
        }];
        [requestServer setFailedBlock:^{
           //Post delegate
            if ([_dropdownboxViewDelegate respondsToSelector:@selector(DropdownboxViewLoadingDataFail:)]) {
                [_dropdownboxViewDelegate DropdownboxViewLoadingDataFail:self];
            }
            //Post a;ert
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Load find event faild !!!" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Refesh", nil];
            alert.tag = ALERT_COMBOBOX_FINDEVENT;
            [alert show];
            SAFE_RELEASE_OBJECT(alert);
        }];
        [requestServer startSynchronous];
    });
}
- (void)decodeJson{
    NSLog(@"So luong contries/Catogory da nhan duoc: %d", [_arrayListData count]);
    
    [self setupUI];
    
    if ([_dropdownboxViewDelegate respondsToSelector:@selector(DropdownboxView:didFinishDownload:withTypeDropboxIs:)]) {
        [_dropdownboxViewDelegate DropdownboxView:self didFinishDownload:[_arrayListData count]withTypeDropboxIs:[_typeAPI isEqualToString:countries_API] ? countries_API : categories_API];
    }
}
#pragma mark - cancelRequest
- (void)cancelRequest{
    [requestServer clearDelegatesAndCancel];
}

//////////////////////////////////////////////////////////////////////////////////////////////
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        if ([_dropdownboxViewDelegate respondsToSelector:@selector(DropdownboxViewCancelRefeshData:)]) {
            [_dropdownboxViewDelegate DropdownboxViewCancelRefeshData:self];
        }
    }
    else{
        if ([_dropdownboxViewDelegate respondsToSelector:@selector(DropdownboxViewRefeshData:)]) {
            [_dropdownboxViewDelegate DropdownboxViewRefeshData:self];
        }
        [self getDataFromServer];
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	[refeshHeaderTableView egoRefreshScrollViewDidScroll:scrollView];
    
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[refeshHeaderTableView egoRefreshScrollViewDidEndDragging:scrollView];
    
}

#pragma mark EGORefreshTableHeader Delegate
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
	
    // send request to server
    [NSObject cancelPreviousPerformRequestsWithTarget:self
                                             selector:@selector(refreshTime)
                                               object:nil];
    
    addingDuration = 0;
    [self getDataFromServer];
}
-(void)refreshTime{
    addingDuration ++;
    
    [self performSelector:@selector(refreshTime) withObject:nil afterDelay:60.0];
    
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	NSLog(@"Data Source Last Updated");
	return [NSDate date];
	
}
- (void)reloadTableViewDataSource{
	NSLog(@"ReloadTable view source");
	_reloading = YES;
	
}
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	return _reloading; // should return if data source model is reloading
	
}
- (void)doneLoadingTableViewData{
	//  model should call this when its done loading
    NSLog(@"Done Loading Table View Data");
	_reloading = NO;
	[refeshHeaderTableView egoRefreshScrollViewDataSourceDidFinishedLoading:_tblView];
	
}


- (void)dealloc{
    SAFE_RELEASE_OBJECT(_tblView);
    SAFE_RELEASE_OBJECT(_arrayListData);
    SAFE_RELEASE_OBJECT(refeshHeaderTableView);
    SAFE_RELEASE_OBJECT(_typeAPI);
    [super dealloc];
}


@end
